package com.cxf.windex.task;

import com.cxf.windex.base.bean.LockInfo;
import com.cxf.windex.base.constant.LockConstant;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.biz.CxfAccountBiz;
import com.cxf.windex.biz.CxfAccountLogBiz;
import com.cxf.windex.biz.CxfPlatformBiz;
import com.cxf.windex.biz.CxfUserBiz;
import com.cxf.windex.entity.*;
import com.cxf.windex.enums.OperateEnum;
import javafx.application.Platform;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.Future;

/**
 * @program: drp
 * @description: 付款异步任务
 * @author: chenxf
 * @create: 2018-05-23 15:22
 **/
@Component
public class PayTask {
    public static final Logger logger = LoggerFactory.getLogger(RegisterTask.class);

    @Autowired
    private CxfAccountBiz cxfAccountBiz;

    @Autowired
    private CxfAccountLogBiz cxfAccountLogBiz;

    @Autowired
    private CxfUserBiz cxfUserBiz;

    @Autowired
    private CxfPlatformBiz cxfPlatformBiz;
    /**
     * 支付提成
     * @param platformUser 平台用户
     * @param cxfPayInfo 支付信息
     * @return
     * @throws Exception
     */
    @Async
    public Future<String> doPayTask(PlatformUser platformUser, CxfPayInfo cxfPayInfo)  {
        logger.debug("开始 支付提成");
        //判断推销人员

        CxfUser cxfUser=cxfUserBiz.selectById(platformUser.getCrtUser());
        if(cxfUser==null){
            logger.error("销售人员={} 不存在",platformUser.getCrtUser());
            return new AsyncResult<>("完成支付提成");
        }

        //获取平台信息
        CxfPlatform cxfPlatform=cxfPlatformBiz.selectById(platformUser.getPlatform());
        if(cxfUser==null){
            logger.error("平台={} 不存在",platformUser.getPlatform());
            return new AsyncResult<>("完成支付提成");
        }
        //计算 提成保存资金信息
        BigDecimal money=cxfPayInfo.getPayMoney().multiply(cxfPlatform.getBaseApr()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
        CxfAccount cxfAccount=new CxfAccount();
        cxfAccount.setUserid(cxfUser.getId());

        //用户资金锁
        LockInfo lockInfo = new LockInfo(LockConstant.MONEY_LOCK+cxfUser.getId());
        try {
            cxfAccount=cxfAccountBiz.selectOne(cxfAccount);
            if(cxfAccount==null){
                logger.error("销售人员={} 资金信息不存在",platformUser.getCrtUser());
                return new AsyncResult<>("完成支付提成");
            }
            cxfAccount.setAccount(cxfAccount.getAccount().add(money));
            cxfAccount.setBalance(cxfAccount.getBalance().add(money));
            doAccount(cxfAccount,OperateEnum.getIdType(cxfPayInfo.getPayCode()),money.toString(),String.format(UserConstant.CERT_MSG,cxfPlatform.getName(), platformUser.getName(), money));
        } catch (Exception e) {
            logger.error("资金变动失败 e={}",e.getMessage());
        }finally {
            lockInfo.unlock();
        }
        if(StringUtils.isNotBlank(cxfUser.getCrtUser())){
            doMoneyAddTask(cxfPlatform,cxfUser.getCrtUser(),cxfPayInfo.getPayMoney(),cxfUser.getName(),1);
        }else{
            logger.info("无销售人员");
        }

        return new AsyncResult<>("完成支付提成");
    }

    @Async
    public Future<String> doMoneyAddTask(CxfPlatform cxfPlatform,String userid, BigDecimal money, String name,int level) {
        CxfUser user = cxfUserBiz.selectById(userid);
        if (user == null) {
            logger.debug("推广用户不存在 userid={} 分销计算结束", userid, level);
            return new AsyncResult<>("分销计算结束");
        }
        switch (level) {
            case 1:
                doZtTask(cxfPlatform,userid, money,name, level);
                //TODO add 一级分销金额
                if (StringUtils.isBlank(user.getCrtUser())) {
                    return new AsyncResult<>("分销结算结束");
                } else {
                    level++;
                    return doMoneyAddTask(cxfPlatform,user.getCrtUser(), money,name, level);
                }
            case 2:
                //TODO add 二级分销金额
                doZtTask(cxfPlatform,userid, money,name, level);
                return new AsyncResult<>("分销结算结束");
            default:
                return new AsyncResult<>("分销结算结束");
        }
    }

    @Async
    public Future<String> doZtTask(CxfPlatform cxfPlatform,String userid, BigDecimal money,String name, int level) {
        CxfAccount cxfAccount = new CxfAccount();
        cxfAccount.setUserid(userid);

        LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userid);
        try {
            cxfAccount = cxfAccountBiz.selectOne(cxfAccount);
            if (cxfAccount == null) {
                logger.debug("用户资金信息不存在  userid={} vip={} level={}分销结算结束", userid, level);
                lockInfo.unlock();
                return new AsyncResult<>("直推结束");
            }
            BigDecimal income=money.multiply(cxfPlatform.getNomalApr()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
            cxfAccount.setAccount(cxfAccount.getAccount().add(income));
            cxfAccount.setBalance(cxfAccount.getBalance().add(income));
            doAccount(cxfAccount,OperateEnum.INVITE,income.toString(),String.format(UserConstant.INVITE_MSG, name, income));


        } catch (Exception e) {
            logger.error("分销结算失败 e={}", e.getMessage());
        } finally {
            lockInfo.unlock();
        }
        return new AsyncResult<>("分销结算结束");
    }
    /**
     * 保存资金信息
     * @param cxfAccount 资金信息
     * @param opreate 操作
     * @param zcCount 金额
     * @param notes 备注
     * @return
     */
    public Future<String> doAccount(CxfAccount cxfAccount, OperateEnum opreate, String zcCount, String notes)  {

        long start = System.currentTimeMillis();
        //生成日志
        this.accountLog(cxfAccount,opreate,notes,zcCount);
        cxfAccountBiz.updateSelectiveById(cxfAccount);
        long end = System.currentTimeMillis();
        logger.debug("资金变动：" + (end - start) + "毫秒");

        return new AsyncResult<>("资金变动");
    }


    /**
     * 保存资金日志
     * @param cxfAccount 资金信息
     * @param opreate 操作
     * @param notes 备注
     * @param zcCount 金额
     */
    private void accountLog(CxfAccount cxfAccount,OperateEnum opreate,String notes,String zcCount){
        CxfAccountLog entity=new CxfAccountLog();
        if(opreate.getKey().equals("tx_froze") ||opreate.getKey().equals("tx_fee")||opreate.getKey().equals("bonus_fee")||opreate.getKey().equals("tx_success")){

            entity.setMoney(new BigDecimal(0).subtract(new BigDecimal(zcCount)));
        }else{

            entity.setMoney(new BigDecimal(zcCount));
        }
        entity.setOperate(opreate.getDesc());
        entity.setOperateType(opreate.getKey());
        entity.setName(cxfAccount.getName());
        entity.setNotes(notes);
        entity.setUserid(cxfAccount.getUserid());
        if(opreate.equals(OperateEnum.TXFROZE)){
            //设置提现申请未处理状态
            entity.setStatus("0");
        }
        cxfAccountLogBiz.insertSelective(entity);
    }


}
